package cn.framelife.rainbow.util;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import cn.framelife.rainbow.constant.Constant;
import cn.framelife.rainbow.db.entity.ConnectionProperty;

/**
 * JDBC工具类
 * @ClassName: JDBCUtil 
 * @author 潘广伟 p_3er@qq.com
 * @date 2013年11月5日 下午10:52:38 
 *
 */
public class JDBCUtil {
	
	/**
	 * 获取一个数据库连接
	 *
	 * @param property
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection(ConnectionProperty property) throws Exception{
		ClassLoader loader = new URLClassLoader(new URL[] { 
                new URL("file:"+property.getJarURL())}, Thread.currentThread().getContextClassLoader());
		Object clazz = loader.loadClass(property.getDriverClass()).newInstance();
	    Driver driver = (Driver)clazz;
	    
	    Properties prop = new Properties();
	    prop.put("remarksReporting","true");
	    prop.setProperty("user",property.getUsername());
	    prop.setProperty("password",property.getPassword());
		Connection conn = driver.connect(property.getConnectionURL(),prop);
		conn.createStatement();
		return conn;
	}

	/**
	 * 获取当前连接的所有表名
	 *
	 * @return
	 * @throws Exception
	 */
	public static List<String> getTableNames() throws Exception{
		List<String> names = new ArrayList<String>();
		Connection connection = DatabaseCache.getConnection();
		String driverClass = DatabaseCache.getConnectionProperty().getDriverClass();
		
		String tablesSQL = "show tables";
		if(driverClass.equals(Constant.MYSQLDRIVER)){
			tablesSQL = "show tables";
		}else if(driverClass.equals(Constant.ORACLEDRIVER)){
			tablesSQL = "select table_name from user_tables";
		}
		
		if (connection != null) {
			Statement statement = connection.createStatement();
			ResultSet resultSet = statement.executeQuery(tablesSQL);
			while (resultSet.next()) {
				names.add(resultSet.getString(1));
			}
		}
		return names;
	}
}
